package com.avic.modules.realtime.nettysocket;

import cn.hutool.json.JSONUtil;
import com.avic.modules.realtime.enums.NettyEnum;
import com.avic.modules.realtime.event.FreeVehicleEvent;
import com.avic.modules.realtime.event.TaskEvent;
import com.google.common.eventbus.Subscribe;
import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.timeout.IdleStateEvent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.yeauty.annotation.*;
import org.yeauty.pojo.Session;

import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * @author ayetony.miao
 * @date 2022/8/10 17:17
 **/
@ServerEndpoint(path = "/ws/{arg}", port = "9999")
@Component
@Slf4j
public class NettyWebSocket {

    private static final CopyOnWriteArraySet<Session> messageWebSocketSet = new CopyOnWriteArraySet<>();
    private static final CopyOnWriteArraySet<Session> freeWebSocketSet = new CopyOnWriteArraySet<>();

    @Subscribe
    public void listenTask(TaskEvent taskEvent) {
        sendMessage(messageWebSocketSet, JSONUtil.toJsonStr(taskEvent));
    }

    @Subscribe
    public void listenFree(FreeVehicleEvent freeVehicleEvent) {
        sendMessage(freeWebSocketSet, JSONUtil.parse(freeVehicleEvent).toString());
    }

    @BeforeHandshake
    public void handshake(Session session, HttpHeaders headers, @RequestParam String req, @PathVariable String arg) {
        session.setSubprotocols("stomp");
        if (!"ok".equals(req)) {
            System.out.println("Authentication failed!");
            session.close();
        }
    }

    @OnOpen
    public void onOpen(Session session, HttpHeaders headers, @RequestParam String req, @PathVariable String arg) {
        if (arg.equalsIgnoreCase(NettyEnum.PUSH_MESSAGE_TASK.getMessage())) {
            messageWebSocketSet.add(session);
        } else if (arg.equalsIgnoreCase(NettyEnum.PUSH_FREE_POINTS.getMessage())) {
            freeWebSocketSet.add(session);
        }
        log.info("【WebSocketServerListener】有新的连接,总数:{}", messageWebSocketSet.size());
    }

    @OnClose
    public void onClose(Session session) throws IOException {
        System.out.println("one connection closed");
    }

    @OnError
    public void onError(Session session, Throwable throwable) {
        throwable.printStackTrace();
    }

    @OnMessage
    public void onMessage(Session session, String message) {
        session.sendText(message);
    }

    /**
     * 二进制数据
     *
     * @param session 管道 session
     * @param bytes   字节
     */
    @OnBinary
    public void onBinary(Session session, byte[] bytes) {
        for (byte b : bytes) {
            System.out.println(b);
        }
        session.sendBinary(bytes);
    }

    @OnEvent
    public void onEvent(Session session, Object evt) {
        if (evt instanceof IdleStateEvent) {
            IdleStateEvent idleStateEvent = (IdleStateEvent) evt;
            switch (idleStateEvent.state()) {
                case READER_IDLE:
                    System.out.println("read idle");
                    break;
                case WRITER_IDLE:
                    System.out.println("write idle");
                    break;
                case ALL_IDLE:
                    System.out.println("all idle");
                    break;
                default:
                    break;
            }
        }
    }

    public void sendMessage(CopyOnWriteArraySet<Session> sessions, String message) {
        for (Session s : sessions) {
            if (s.isActive()) {
                s.sendText(message);
            } else {
                sessions.remove(s);
            }
        }
    }

}